﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

using LuckyBingoRcon.Commands.Events;

namespace LuckyBingoRcon.Commands
{
	public class SATimeStampCommand : Command
	{
		public EventHandler<SATimeStampCommandEventArgs> OnResponse;

        public SATimeStampCommand(bool setCommand)
        {
            if(!setCommand)
                base.commandText = "scr_motd ";
            else
                base.commandText = "setadmindvar scr_motd ";
            base.args = null;
        }

		protected override void CommandOnResponse(string response)
		{
			string timeStamp = null;
			StringReader sr = new StringReader(response);

			try
			{
				while (sr.Peek() > 0)
				{
					string ln = sr.ReadLine().Trim();
					if (!String.IsNullOrEmpty(ln) && (ln.StartsWith("\"scr_motd") || ln.StartsWith("scr_motd")))    // Heli: Line has "scr_motd", not scr_motd at beginning
					{
						int index = ln.IndexOf("is:");                                      // Heli: Find (if packet was received correctly) the time stamp start index
						if (index < ln.Length - 4)
						{
							ln = ln.Remove(0, index + 4);                                   // Remove all characters before scr_motd ...
							index = ln.IndexOf("^7");
							if (index > 0)
								ln = ln.Remove(index);
							timeStamp = ln.Trim();
							break;
						}
					}
				}


				if (OnResponse != null)
				{
					SATimeStampCommandEventArgs e = new SATimeStampCommandEventArgs();
					e.timeStamp = timeStamp;
					OnResponse(this, e);
				}
			}
			catch (Exception error)
			{
				if (OnResponse != null)
				{
					SATimeStampCommandEventArgs e = new SATimeStampCommandEventArgs();
					e.timeStamp = timeStamp;
					e.Error = error;
					OnResponse(this, e);
				}
			}

			sr.Close();
		}

        public override string ToString()
        {
            if (base.commandText.Contains("setadmindvar"))   // Is a set command
                return "Set\tTime Stamp\t=\t" + base.args.ToString();
            else
                return "Get\tTime Stamp";
        }
	}
}
